<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <page-tools title="数量20条">
        <!-- v-if="$store.state.user.userInfo.roles.points.includes(import_excel)" -->
        <el-button
          v-allow="'import_excel'"
          type="warning"
          size="small"
          @click="hImport"
        >excel导入</el-button>
        <!-- v-if="$store.state.user.userInfo.roles.points.includes(export_excel)" -->
        <el-button
          v-allow="'export_excel'"
          type="danger"
          size="small"
          @click="handleDownload"
        >excel导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog = true"
        >新增员工</el-button>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="list" :default-sort="{ prop: 'timeOfEntry' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 2, 5, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hCloseDialog"
      >
        <emp-dialog
          ref="AddEmployee"
          @empolyee="hUpdateEmpolyee"
          @hDelt="employee"
        />
      </el-dialog>

      <!-- 分配角色弹框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-role
          v-if="showDialogRole"
          :cur-employe-id="curEmployeId"
          @close="showDialogRole = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import { EmployeeEnum } from '@/constant/employees'
import empDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'

export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      list: [], // 保存员工列表数据
      total: 0, // 总条数
      page: 1, // 默认页面
      size: 2, // 每页的条数
      showDialog: false, // 新增员工弹框开关
      showDialogRole: false, // 分配角色弹框开关
      curEmployeId: ''
    }
  },
  created() {
    // 获取员工列表
    this.loadEmployeeList()
  },
  methods: {
    // 获取员工列表
    async loadEmployeeList() {
      const { data: res } = await getEmployeeList({
        page: this.page,
        size: this.size
      })
      // console.log(res)
      this.list = res.rows
      this.total = res.total
    },
    // 聘用形式
    formatEmployment(type) {
      return EmployeeEnum[type] || '未知'
    },
    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更新参数
      this.size = val
      // 默认页码
      this.page = 1
      // 重发请求
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 1. 更新页码
      this.page = val
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 点击删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 确认
          this.doDel(id)
        })
        .catch((err) => {
          // 取消
          console.log(err)
        })
    },
    // 删除请求
    async doDel(id) {
      try {
        // 1、发送请求
        await delEmployee(id)
        // 2、提示
        this.$message.success('删除成功')
        // 3、重新渲染
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.loadEmployeeList()
      } catch (error) {
        console.dir(error)
      }
    },
    // 子传父
    hUpdateEmpolyee() {
      // 关闭弹框
      this.showDialog = false
      // 重新渲染
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    // 关闭弹框时触发
    hCloseDialog() {
      // 重置
      this.$refs.AddEmployee.resetForm()
      // 关闭弹框
      this.showDialog = false
    },
    employee() {
      // 关闭弹框
      this.showDialog = false
    },
    // 点击导入跳转
    hImport() {
      this.$router.push('/import')
    },
    formData(rows) {
      const mapObj = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const enheader = Object.keys(rows[0]) // 英文表头
      const header = enheader.map((obj) => mapObj[obj]) // 转换成中文
      const data = rows.map((obj) => {
        // 正式和非正式的处理
        obj.formOfEmployment = EmployeeEnum[obj.formOfEmployment]
        return Object.values(obj)
      })
      console.log(header, data)
      return { header, data }
    },
    // 导出功能
    async handleDownload() {
      const { data: res } = await getEmployeeList({
        page: this.page,
        size: this.size
      })
      const { header, data } = this.formData(res.rows)
      this.downloadLoading = true
      console.log(res)
      // 这个文件初始不会加载进来，@/vendor/Export2Excel
      // 点击按钮，执行回调，就会去加载这个文件
      // .then()当文件读入完成之后，做....
      import('@/vendor/Export2Excel').then((excel) => {
        // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)

        // 生成excel
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.curEmployeId = id
    }
  }
}
</script>
